//
//  MemberListView.m
//  location
//
//  Created by Dongxiang Xu on 2024/4/25.
//


#import "XDXBaseTabBarViewController.h"
#import "MemberListView.h"
#import "MemberListTableViewCell.h"
#import "MemberRegionTableViewCell.h"
#import "PopCashView.h"
#import "HomeViewController.h"
#import "CashViewController.h"
#import <UserNotifications/UserNotifications.h>
#import "WGS84TOGCJ02.h"

@interface MemberListView ()<UITableViewDataSource,UITableViewDelegate,UIGestureRecognizerDelegate>

@property (nonatomic, strong) UIView *infoView;
@property (nonatomic, strong) UIButton *notify;
@property (nonatomic, strong) UIButton *member;
@property (nonatomic, strong) UIButton *location;
@property (nonatomic, assign) CGFloat originY;
@property (nonatomic, assign) BOOL isDragging;
@property (nonatomic, assign) BOOL isButtonClick;
@property (nonatomic, strong) CADisplayLink *displayLink;

@end

@implementation MemberListView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ReloadMemberNotification) name:Noti_ReloadMemberNotification object:nil];
        [self initUI];
    }
    return self;
}

- (void)initUI
{
    _infoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-STATUSHEIGHT)];
    [self addSubview:_infoView];
    
    CALayer *infoLayer = [CALayer layer];
    infoLayer.frame = _infoView.bounds;
    infoLayer.cornerRadius = 25;
    infoLayer.masksToBounds = NO;
    infoLayer.backgroundColor = RealWhiteColor.CGColor;
    infoLayer.shadowColor = RealBlackColor.CGColor;
    infoLayer.shadowOffset = CGSizeMake(0,2);
    infoLayer.shadowOpacity = 0.3;
    infoLayer.shadowRadius = 3;
    [_infoView.layer addSublayer:infoLayer];
    
    UILabel *slider = [[UILabel alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-42)/2, 8, 42, 4)];
    slider.layer.masksToBounds = YES;
    slider.backgroundColor = GraryMiddleColor;
    [slider.layer setCornerRadius:2];
    [_infoView addSubview:slider];
    
    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    panGestureRecognizer.delegate = self;
    [self addGestureRecognizer:panGestureRecognizer];

    _notify = [[UIButton alloc] initWithFrame:CGRectMake(16, 31, _infoView.width-32, 42)];
    _notify.backgroundColor = NormalMainColor;
    _notify.layer.masksToBounds = YES;
    [_notify.layer setCornerRadius:16];
    [_notify setImage:[UIImage imageNamed:@"notify_bling"] forState:UIControlStateNormal];
    [_notify setTitle:@" 点击打开通知权限，不错过任何家人消息" forState:UIControlStateNormal];
    [_notify.titleLabel setFont:DEFAULT_FONT(13)];
    [_notify setTitleColor:RealWhiteColor forState:UIControlStateNormal];
    _notify.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [_infoView addSubview:_notify];
    _notify.hidden = YES;
    [[_notify rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL:url options:@{UIApplicationOpenURLOptionUniversalLinksOnly:@NO} completionHandler:nil];
    }];
    
    _member = [[UIButton alloc] initWithFrame:CGRectMake(20, _notify.hidden?32:97, 104, 40)];
    _member.layer.masksToBounds = YES;
    [_member.layer setCornerRadius:20];
    _member.backgroundColor = NormalMainColor;
    [_member setImage:[UIImage imageNamed:@"member_sel"] forState:UIControlStateNormal];
    [_infoView addSubview:_member];
    
    _location = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_member.frame)+16, _member.y, 84, 40)];
    _location.layer.masksToBounds = YES;
    [_location.layer setCornerRadius:20];
    _location.backgroundColor = [NormalMainColor colorWithAlphaComponent:0.08];
    [_location setImage:[UIImage imageNamed:@"location_nor"] forState:UIControlStateNormal];
    [_infoView addSubview:_location];
    
    [self ReloadMemberNotification];
    
    [[self.member rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        UIImpactFeedbackGenerator *feedBackGenertor = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleLight];
        [feedBackGenertor impactOccurred];
        self.isButtonClick = YES;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.isButtonClick = NO;
        });
        [UIView animateWithDuration:0.3 animations:^{
            self.member.backgroundColor = NormalMainColor;
            [self.member setImage:[UIImage imageNamed:@"member_sel"] forState:UIControlStateNormal];
            [self.member setFrame:CGRectMake(20, self.member.y, 104, 40)];
            
            self.location.backgroundColor = [NormalMainColor colorWithAlphaComponent:0.08];
            [self.location setImage:[UIImage imageNamed:@"location_nor"] forState:UIControlStateNormal];
            [self.location setFrame:CGRectMake(CGRectGetMaxX(self.member.frame)+16, self.member.y, 84, 40)];
        }];
        if (self.memberList.count>0) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
            [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
        }
    }];
    
    [[self.location rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        UIImpactFeedbackGenerator *feedBackGenertor = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleLight];
        [feedBackGenertor impactOccurred];
        self.isButtonClick = YES;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.isButtonClick = NO;
        });
        [UIView animateWithDuration:0.3 animations:^{
            self.y = STATUSHEIGHT;
            self.member.backgroundColor = [NormalMainColor colorWithAlphaComponent:0.08];
            [self.member setImage:[UIImage imageNamed:@"member_nor"] forState:UIControlStateNormal];
            [self.member setFrame:CGRectMake(20, self.member.y, 84, 40)];
            
            self.location.backgroundColor = NormalMainColor;
            [self.location setImage:[UIImage imageNamed:@"location_sel"] forState:UIControlStateNormal];
            [self.location setFrame:CGRectMake(CGRectGetMaxX(self.member.frame)+16, self.member.y, 104, 40)];
        }];
        if (self.regions.count>0) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
            [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
        }        
    }];
    
    [_infoView addSubview:self.tableView];
    
    [UIView animateWithDuration:0.3 animations:^{
        [self setFrame:CGRectMake(0, SCREEN_HEIGHT-ORIGIN_H, SCREEN_WIDTH, SCREEN_HEIGHT-STATUSHEIGHT)];
    }];
}

- (void)handlePan:(UIPanGestureRecognizer *)recognizer
{
    CGPoint translation = [recognizer translationInView:self];
    CGRect newFrame = self.frame;
    newFrame.origin.y += translation.y;
    if (newFrame.origin.y<SCREEN_HEIGHT-_tableView.y && newFrame.origin.y>STATUSHEIGHT) {
        self.y = newFrame.origin.y;
        if (self.y<(SCREEN_HEIGHT-ORIGIN_H)) {
            self.map.alpha = (56-(SCREEN_HEIGHT-ORIGIN_H-self.y))/56;
            self.vector.alpha = (56-(SCREEN_HEIGHT-ORIGIN_H-self.y))/56;
            self.map.y = 2*(SCREEN_HEIGHT-ORIGIN_H)-56-self.y;
            self.vector.y = self.map.y-56;
        }else{
            self.map.alpha = 1;
            self.vector.alpha = 1;
            self.map.y = self.y-56;
            self.vector.y = self.map.y-56;
            [(HomeViewController *)self.viewContainingController dealAnnotation];
        }
        [recognizer setTranslation:CGPointZero inView:self];
    }
    
    if (recognizer.state == UIGestureRecognizerStateBegan){
        _originY = self.y;
    }else if (recognizer.state == UIGestureRecognizerStateEnded){
        if (self.y>_originY) {
            if (self.y>(SCREEN_HEIGHT-ORIGIN_H)) {
                [self bottom];
            }else{
                [self show];
            }           
        }else{
            if (self.y<SCREEN_HEIGHT-ORIGIN_H) {
                [self top];
            }else{
                [self show];
            }
        }
    }    
}

- (void)dismiss
{
    [UIView animateWithDuration:0.3 animations:^{
        [self setFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT-STATUSHEIGHT)];
    }];
}

- (void)top
{
    if (self.y != STATUSHEIGHT) {
        self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleDisplayLink:)];
        [self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self stopDisplayLink];
        });
        [UIView animateWithDuration:0.3 animations:^{
            self.y = STATUSHEIGHT;
            
            self.map.alpha = 0;
            self.vector.alpha = 0;
        } completion:^(BOOL finished) {
            [self stopDisplayLink];
            if (self.MemberListViewIsTop) {
                self.MemberListViewIsTop(self.y);
            }
            self.tableView.scrollEnabled = YES;
        }];
    }
}

- (void)bottom
{
    self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleDisplayLink:)];
    [self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self stopDisplayLink];
    });
    if (self.y != SCREEN_HEIGHT-self.tableView.y) {
        [UIView animateWithDuration:0.3 animations:^{
            self.y = SCREEN_HEIGHT-self.tableView.y-TABBARHEIGHT;
            self.map.alpha = 1;
            self.vector.alpha = 1;
            self.map.y = self.y-56;
            self.vector.y = self.map.y-56;
        } completion:^(BOOL finished) {
            [self stopDisplayLink];
            if (self.MemberListViewIsTop) {
                self.MemberListViewIsTop(self.y);
            }
            self.tableView.scrollEnabled = NO;
        }];
    }
}

- (void)show
{
    if (self.y != SCREEN_HEIGHT-ORIGIN_H) {
        self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleDisplayLink:)];
        [self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self stopDisplayLink];
        });
        [UIView animateWithDuration:0.3 animations:^{
            self.y = SCREEN_HEIGHT-ORIGIN_H;
            self.map.alpha = 1;
            self.vector.alpha = 1;
            self.map.y = self.y-56;
            self.vector.y = self.map.y-56;
        } completion:^(BOOL finished) {
            [self stopDisplayLink];
            if (self.MemberListViewIsTop) {
                self.MemberListViewIsTop(self.y);
            }
            self.tableView.scrollEnabled = NO;
        }];
    }
}

- (void)handleDisplayLink:(CADisplayLink *)link
{
    [(HomeViewController *)self.viewContainingController dealAnnotation];
}

- (void)stopDisplayLink
{
    [self.displayLink invalidate];
    self.displayLink = nil;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return self.memberList.count>0?self.memberList.count:5;  
    }else{
        return self.regions.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 92;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        return CGFLOAT_MIN;
    }else{
        return 50 ;
    }
   
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 60+(section>0?TABBARHEIGHT:0)+((section>0 && self.regions.count==0)?16:0);
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
    view.layer.masksToBounds = YES;
    if (section==0) {
        [view setFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0)];
    }else{
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 24, SCREEN_WIDTH-48, 26)];
        label.textColor = RealBlackColor;
        label.font = MEDIUM_FONT(20);
        label.text = @"位置";
        [view addSubview:label];
    }
    return view;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 60+(section>0?TABBARHEIGHT:0)+((section>0 && self.regions.count==0)?16:0))];
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(16, (section>0 && self.regions.count==0)?16:0, SCREEN_WIDTH-32, 60)];
    button.layer.masksToBounds = YES;
    [button.layer setCornerRadius:20];
    button.backgroundColor = LightBGColor;
    [button setTitleColor:NormalMainColor forState:UIControlStateNormal];
    [button.titleLabel setFont:REAL_MEDIUM_FONT(15)];
    [view addSubview:button];
    [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        if (self.MemberFooterBlock) {
            self.MemberFooterBlock(section);
        }
    }];
    
    if (section==0) {
        [button setImage:[UIImage imageNamed:@"add_home_famliy"] forState:UIControlStateNormal];
        [button setTitle:@" 邀请家人" forState:UIControlStateNormal];
    }else{
        [button setImage:[UIImage imageNamed:@"add_location"] forState:UIControlStateNormal];
        [button setTitle:@" 添加提醒地点" forState:UIControlStateNormal];
    }
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        NSString *cellIdentifier = @"MemberListTableViewCell";
        MemberListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[MemberListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        if (indexPath.row<self.memberList.count) {
            [cell loadWithInfo:self.memberList[indexPath.row]];
            if (indexPath.row==(self.memberList.count-1)) {
                cell.line.hidden = YES;
            }else{
                cell.line.hidden = NO;
            }
        }
        return cell;
    }else{
        NSString *cellIdentifier = @"MemberRegionTableViewCell";
        MemberRegionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[MemberRegionTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        [cell loadWithInfo:self.regions[indexPath.row]];
        __block MemberRegionTableViewCell *cellBlock = cell;
        cell.MemberRegionDeleteBlock = ^{
            NSString *string = [NSString stringWithFormat:@"确定要删除 “%@” 吗？",self.regions[indexPath.row][@"name"]];
            UIAlertController *ac = [UIAlertController alertControllerWithTitle:string
                                                                        message:@"将为您的整个家庭删除这个位置"
                                                                 preferredStyle:UIAlertControllerStyleActionSheet];
            NSMutableAttributedString *attrTitle = [[NSMutableAttributedString alloc] initWithString:string];
            [attrTitle addAttribute:NSFontAttributeName value:MEDIUM_FONT(17) range:NSMakeRange(0, attrTitle.length)];
            [ac setValue:attrTitle forKey:@"attributedTitle"];

            [ac addAction:[UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {                
                NSDictionary *param = [NSMutableDictionary dictionary];
                [param setValue:self.regions[indexPath.row][@"id"] forKey:@"locationId"];
                CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
                [manager encryptedPOST:@"/system/group/removegeofence"
                parameters:param
                success:^(NSDictionary *responseObject) {
                    if ([responseObject[@"code"] integerValue]==200) {
                        [self.regions removeObjectAtIndex:indexPath.row];
                        [self.tableView reloadData];
                    }
                }
                failure:^(NSError *aError) {
                    
                }];
            }]];
            [ac addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
            UIPopoverPresentationController *pop = ac.popoverPresentationController;
            
            pop.sourceView = cellBlock.delete;
            pop.sourceRect = cellBlock.delete.bounds;
            pop.permittedArrowDirections = UIPopoverArrowDirectionUnknown;
            [self.viewContainingController presentViewController:ac animated:YES completion:nil];
        };
        cell.MemberRegionLaunchBlock = ^{
            // 判断会员
            if ([self.groupInfo[@"membership"] isKindOfClass:[NSDictionary class]] && [self.groupInfo[@"membership"][@"planType"] integerValue]==3) {                
                NSMutableArray *param = [NSMutableArray array];
                for (NSMutableDictionary *user in self.regions[indexPath.row][@"usersNotification"]) {
                    [user setValue:self.regions[indexPath.row][@"id"] forKey:@"locationId"];
                    [user setValue:user[@"userId"] forKey:@"monitoredUserId"];
                    if ([self.regions[indexPath.row][@"isLaunch"] boolValue]) {
                        [user setValue:@"4" forKey:@"code"];
                    }else{
                        [user setValue:@"3" forKey:@"code"];
                    }
                    [param addObject:user];
                }
                CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
                [manager encryptedPUT:@"/system/group/editgroupuserlocationsetting"
                parameters:param
                success:^(NSDictionary *responseObject) {
                    if ([self.regions[indexPath.row][@"isLaunch"] boolValue]) {
                        [self.regions[indexPath.row] setValue:@(0) forKey:@"isLaunch"];
                    }else{
                        [self.regions[indexPath.row] setValue:@(1) forKey:@"isLaunch"];
                    }
                    [self.tableView reloadData];
                }
                failure:^(NSError *aError) {
                    
                }];
            }else{
                NSMutableDictionary *param = [NSMutableDictionary dictionary];
                [param setValue:self.regions[indexPath.row][@"id"] forKey:@"locationId"];
                CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
                [manager encryptedPOST:@"/system/group/checkLocationNotification"
                parameters:param
                success:^(NSDictionary *responseObject) {
                    if ([responseObject[@"code"] integerValue]==200) {
                        NSMutableArray *param = [NSMutableArray array];
                        for (NSMutableDictionary *user in self.regions[indexPath.row][@"usersNotification"]) {
                            [user setValue:self.regions[indexPath.row][@"id"] forKey:@"locationId"];
                            [user setValue:user[@"userId"] forKey:@"monitoredUserId"];
                            if ([self.regions[indexPath.row][@"isLaunch"] boolValue]) {
                                [user setValue:@"4" forKey:@"code"];
                            }else{
                                [user setValue:@"3" forKey:@"code"];
                            }
                            [param addObject:user];
                        }
                        CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
                        [manager encryptedPUT:@"/system/group/editgroupuserlocationsetting"
                        parameters:param
                        success:^(NSDictionary *responseObject) {
                            if ([self.regions[indexPath.row][@"isLaunch"] boolValue]) {
                                [self.regions[indexPath.row] setValue:@(0) forKey:@"isLaunch"];
                            }else{
                                [self.regions[indexPath.row] setValue:@(1) forKey:@"isLaunch"];
                            }
                            [self.tableView reloadData];
                        }
                        failure:^(NSError *aError) {
                            
                        }];
                    }else{
                        if ([self.groupInfo[@"membership"] isKindOfClass:[NSDictionary class]]) {
                            UIAlertController * alert = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"最多开启%@个提醒（%@会员）",(([self.groupInfo[@"membership"][@"planType"] integerValue]==1)?@"10":@"20"),(([self.groupInfo[@"membership"][@"planType"] integerValue]==1)?@"亲密":@"白银")] message:@"" preferredStyle:UIAlertControllerStyleAlert];
                            UIAlertAction *act =[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                            }];
                            [alert addAction:act];
                            [self.parentContainerViewController presentViewController:alert animated:YES completion:nil];
                        }else{
                            PopCashView *view = [[PopCashView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) GroupInfo:self.groupInfo];
                            [WINDOW addSubview:view];
                            view.PopCashBlock = ^{
                                CashViewController *vc = [[CashViewController alloc] init];                             
                                vc.groupInfo = self.groupInfo;
                                [self.viewContainingController.navigationController pushViewController:vc animated:YES];
                            };
                        }
                    }
                }
                failure:^(NSError *aError) {
                    
                }];
            }
        };
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
//        [UIView animateWithDuration:0.3 animations:^{
            self.y = SCREEN_HEIGHT-ORIGIN_H;
            self.map.alpha = 1;
            self.vector.alpha = 1;
            self.map.y = self.y-56;
            self.vector.y = self.map.y-56;
//        }];
        if (self.MemberInfoBlock) {
            if (indexPath.row < self.memberList.count) {
                id item = self.memberList[indexPath.row];
                if ([item isKindOfClass:[NSDictionary class]]) {
                    // Block 期望 NSMutableDictionary，必要时转可变
                    NSMutableDictionary *info = [item isKindOfClass:[NSMutableDictionary class]] ? (NSMutableDictionary *)item : [item mutableCopy];
                    self.MemberInfoBlock(info);
                }
            }
        }
        self.tableView.scrollEnabled = NO;
    }else{
        if (self.MemberLocationBlock) {
            self.MemberLocationBlock(self.regions[indexPath.row]);
        }    
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == _tableView) {
        if (self.y<=SCREEN_HEIGHT-ORIGIN_H && self.y>=STATUSHEIGHT && _tableView.contentOffset.y<=0) {
            self.y = self.y-_tableView.contentOffset.y;
            if (self.y<(SCREEN_HEIGHT-ORIGIN_H)) {
                self.map.alpha = (56-(SCREEN_HEIGHT-ORIGIN_H-self.y))/56;
                self.vector.alpha = (56-(SCREEN_HEIGHT-ORIGIN_H-self.y))/56;
                self.map.y = 2*(SCREEN_HEIGHT-ORIGIN_H)-56-self.y;
                self.vector.y = self.map.y-56;
            }else{
                self.map.alpha = 1;
                self.vector.alpha = 1;
                self.map.y = self.y-56;
                self.vector.y = self.map.y-56;
                [(HomeViewController *)self.viewContainingController dealAnnotation];
            }
            
           
            [_tableView setContentOffset:CGPointMake(0, 0)];
            if (_isDragging == NO) {
                if (self.y>_originY) {
                    [self show];                   
                }else{
                    if (self.y<SCREEN_HEIGHT-ORIGIN_H) {
                        [self top];
                    }else{
                        [self show];
                    }
                }
            }
        }
        if (self.isButtonClick==NO) {
            if (_tableView.contentOffset.y>(self.memberList.count*92)) {
                [UIView animateWithDuration:0.3 animations:^{
                    self.member.backgroundColor = [NormalMainColor colorWithAlphaComponent:0.08];
                    [self.member setImage:[UIImage imageNamed:@"member_nor"] forState:UIControlStateNormal];
                    [self.member setFrame:CGRectMake(20, self.member.y, 84, 40)];
                    
                    self.location.backgroundColor = NormalMainColor;
                    [self.location setImage:[UIImage imageNamed:@"location_sel"] forState:UIControlStateNormal];
                    [self.location setFrame:CGRectMake(CGRectGetMaxX(self.member.frame)+16, self.member.y, 104, 40)];
                }];
            }else{
                [UIView animateWithDuration:0.3 animations:^{
                    self.member.backgroundColor = NormalMainColor;
                    [self.member setImage:[UIImage imageNamed:@"member_sel"] forState:UIControlStateNormal];
                    [self.member setFrame:CGRectMake(20, self.member.y, 104, 40)];
                    
                    self.location.backgroundColor = [NormalMainColor colorWithAlphaComponent:0.08];
                    [self.location setImage:[UIImage imageNamed:@"location_nor"] forState:UIControlStateNormal];
                    [self.location setFrame:CGRectMake(CGRectGetMaxX(self.member.frame)+16, self.member.y, 84, 40)];
                }];
            }
        }
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (scrollView == _tableView) {
        _isDragging = YES;
        _originY = self.y;
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (scrollView == _tableView) {
        _isDragging = NO;
        if (decelerate==NO) {
            if (self.y>_originY) {
                [self show];
            }else{
                [self top];
            }
        }
    }
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, (82+(_notify.hidden?0:66)), SCREEN_WIDTH, self.height-(82+(_notify.hidden?0:66))) style:UITableViewStyleGrouped];
        _tableView.separatorStyle  = UITableViewCellSeparatorStyleNone;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        if (@available(iOS 15.0, *)) {
            _tableView.fillerRowHeight = 0;
            _tableView.sectionHeaderTopPadding = 0;
        }
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.scrollEnabled = NO;
        _tableView.backgroundColor = RealWhiteColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

- (void)ReloadMemberNotification
{
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
        switch (settings.authorizationStatus) {
            case UNAuthorizationStatusNotDetermined:
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        self.notify.hidden = NO;
                        self.member.y = self.notify.hidden?32:97;
                        self.location.y = self.member.y;
                        [self.tableView setFrame:CGRectMake(0, (82+(self.notify.hidden?0:66)), SCREEN_WIDTH, self.height-(82+(self.notify.hidden?0:66)))];
                    });
                }
                break;
            case UNAuthorizationStatusDenied:
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        self.notify.hidden = NO;
                        self.member.y = self.notify.hidden?32:97;
                        self.location.y = self.member.y;
                        [self.tableView setFrame:CGRectMake(0, (82+(self.notify.hidden?0:66)), SCREEN_WIDTH, self.height-(82+(self.notify.hidden?0:66)))];
                    });
                }
                break;
            case UNAuthorizationStatusAuthorized:
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        self.notify.hidden = YES;
                        self.member.y = self.notify.hidden?32:97;
                        self.location.y = self.member.y;
                        [self.tableView setFrame:CGRectMake(0, (82+(self.notify.hidden?0:66)), SCREEN_WIDTH, self.height-(82+(self.notify.hidden?0:66)))];
                    });
                }
                break;
            case UNAuthorizationStatusProvisional:
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        self.notify.hidden = NO;
                        self.member.y = self.notify.hidden?32:97;
                        self.location.y = self.member.y;
                        [self.tableView setFrame:CGRectMake(0, (82+(self.notify.hidden?0:66)), SCREEN_WIDTH, self.height-(82+(self.notify.hidden?0:66)))];
                    });
                }
                break;
            case UNAuthorizationStatusEphemeral:
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        self.notify.hidden = NO;
                        self.member.y = self.notify.hidden?32:97;
                        self.location.y = self.member.y;
                        [self.tableView setFrame:CGRectMake(0, (82+(self.notify.hidden?0:66)), SCREEN_WIDTH, self.height-(82+(self.notify.hidden?0:66)))];
                    });
                }
                break;
        }
    }];
}

@end
